<?php

namespace App\Http\Service;

use App\Models\User;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class UserService extends BaseService
{
    private $model;
    private $getUserInfo;
    private $benuser;
    private $url;
    
    // 静态变量定义
    private static $initialized = false;
    private static $staticModel;
    private static $staticUrl;
    private static $staticGetUserInfo;
    private static $staticBenuser;
    
    public function __construct(User $model)
    {
        parent::__construct();
        
        // 只在第一次初始化时执行
        if (!self::$initialized) {
            self::$staticModel = $model; // 取消注释这行
            self::$staticUrl = config('myurl.link_parse');
            self::$staticGetUserInfo = config('myurl.getUserInfo');
            self::$staticBenuser = $this->ben_user();
            self::$initialized = true;
        }
        
        // 将静态变量赋值给实例变量
        $this->model = self::$staticModel; // 使用静态模型实例
        $this->url = self::$staticUrl;
        $this->getUserInfo = self::$staticGetUserInfo;
        $this->benuser = self::$staticBenuser;
        
        // 验证模型是否正常初始化
        $this->validateModel();
    }
    
    /**
     * 验证模型是否正常初始化
     */
    private function validateModel()
    {
        if (!$this->model) {
            Log::error('UserService model initialization failed in constructor', [
                'model_class' => User::class,
                'static_model' => self::$staticModel,
                'instance_model' => $this->model
            ]);
            throw new \Exception('User model initialization failed in UserService constructor');
        }
        
        // 检查模型是否有表名（验证模型是否有效）
        try {
            $tableName = $this->model->getTable();
            Log::info('UserService model initialized successfully', [
                'table' => $tableName
            ]);
        } catch (\Exception $e) {
            Log::error('UserService model table check failed: ' . $e->getMessage());
            throw new \Exception('User model table check failed');
        }
    }
    
    // 获取等级描述
    private function getLevelDescription($levelId)
    {
        $levelMap = [
            '1' => '星粉',
            '2' => '星光', 
            '3' => '星辰'
        ];
        
        return $levelMap[$levelId] ?? '星粉';
    }
    
    // 更新或插入用户数据
    private function upsertUserData($people_id, $userData, $level_desc)
    {
        // 使用安全的方法获取模型
        $model = $this->getModel();
        
        $existingUser = $model->where('userId', $people_id)->first();
        $now = date("Y-m-d H:i:s");
        
        $userDataToSave = [
            'nickname' => $userData['nickname'] ?? '未知',
            'avatar' => $userData['avatar'] ?? $this->getDefaultUserData()['avatar'],
            'level' => $userData['levelId'] ?? '1',
            'level_desc' => $level_desc,
            'update_time' => $now,
        ];
        
        if ($existingUser) {
            // 更新现有用户
            if (empty($existingUser->nickname_another)) {
                $userDataToSave['nickname_another'] = $userData['nickname'] ?? '未知';
            }
            
            $model->where('userId', $people_id)->update($userDataToSave);
            Log::info('用户数据更新成功', ['user_id' => $people_id]);
        } else {
            // 插入新用户
            $userDataToSave['parent_id'] = '0';
            $userDataToSave['userId'] = $people_id;
            $userDataToSave['is_official'] = 2;
            $userDataToSave['nickname_another'] = $userData['nickname'] ?? '未知';
            $userDataToSave['create_time'] = $now;
            
            $model->insert($userDataToSave);
            Log::info('用户数据插入成功', ['user_id' => $people_id]);
        }
    }
    
    // 获取默认用户数据
    private function getDefaultUserData($people_id = 0)
    {
        return [
            'userId' => $people_id,
            'nickname' => '未知',
            'avatar' => 'http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/xingfanapp/uploads/442ca8601a70923b7fdb5d697188f80c3983df5c.png',
            'level' => '1',
            'levelId' => '1'
        ];
    }
    
    // 获取远程用户信息
    private function fetchRemoteUserInfo($people_id)
    {
        $getUserInfo = $this->getUserInfo;
        
        if (!$getUserInfo || !isset($getUserInfo['url']) || !isset($getUserInfo['Authorization'])) {
            Log::error('用户信息接口配置缺失');
            return null;
        }
        
        $url = $getUserInfo['url'];
        $Authorization = $getUserInfo['Authorization'];
        
        $header = [
            'Content-Type: application/json; charset=utf-8',
            "Authorization: $Authorization"
        ];
        
        $postdata = ['userId' => $people_id];
        
        try {
            $response = json_post($url, $postdata, $header);
            
            if (!isset($response['status']) || $response['status'] != 200) {
                Log::warning('获取远程用户信息失败', [
                    'people_id' => $people_id,
                    'response' => $response
                ]);
                return null;
            }
            
            return $response['data'] ?? null;
        } catch (\Exception $e) {
            Log::error('调用用户信息接口异常: ' . $e->getMessage(), [
                'people_id' => $people_id
            ]);
            return null;
        }
    }
    
    // 清除用户缓存
    private function clearUserCache()
    {
        Cache::forget('module_user_all');
        Cache::forget('user_list_all');
        Cache::forget('user_data_mapping');
        Cache::forget('official_user_ids');
        
        // 重新初始化 benuser 数据
        self::$staticBenuser = $this->ben_user();
        $this->benuser = self::$staticBenuser;
    }
    
    // 获取本地用户
    public function ben_user()
    {
        $cacheKey = 'module_user_all';
        $cacheTime = 3600;
        
        // 尝试从缓存获取
        $cachedData = Cache::get($cacheKey);
        if ($cachedData !== null) {
            return $cachedData;
        }
        
        try {
            // 使用安全的方法获取模型
            $model = $this->getModel();
            
            // 使用正确的表名
            $list = $model->select(
                'userId', 'nickname', 'avatar', 'level', 
                DB::raw('level as levelId'), 'level_desc'
            )->get()->keyBy('userId')->toArray();
            
            // 转换为数组格式
            $data = [];
            foreach ($list as $userId => $user) {
                $data[$userId] = (array)$user;
            }
            
            // 存入缓存
            Cache::put($cacheKey, $data, $cacheTime);
            
            Log::info('用户列表缓存更新成功', ['count' => count($data)]);
            
            return $data;
            
        } catch (\Exception $e) {
            Log::error('获取用户列表失败: ' . $e->getMessage());
            return [];
        }
    }
    
    // 更新user表
    public function update_user($people_id)
    {
        // 检查本地缓存
        if (isset($this->benuser[$people_id])) {
            return $this->benuser[$people_id];
        }
        
        // 使用缓存锁防止并发请求
        $lockKey = "user_update_lock:{$people_id}";
        $lock = Cache::lock($lockKey, 10);
        
        try {
            if ($lock->get()) {
                // 再次检查（在获取锁期间可能已被其他请求更新）
                $currentBenuser = $this->ben_user();
                if (isset($currentBenuser[$people_id])) {
                    return $currentBenuser[$people_id];
                }
                
                // 获取远程用户信息
                $userData = $this->fetchRemoteUserInfo($people_id);
                if (!$userData) {
                    Log::warning('获取远程用户信息失败，使用默认数据', ['user_id' => $people_id]);
                    return $this->getDefaultUserData($people_id);
                }
                
                // 处理用户数据
                $level_desc = $this->getLevelDescription($userData['levelId'] ?? '1');
                
                // 更新或插入用户数据
                $this->upsertUserData($people_id, $userData, $level_desc);
                
                // 清除缓存以便下次获取最新数据
                $this->clearUserCache();
                
                Log::info('用户数据更新完成', ['user_id' => $people_id]);
                
                return $userData;
            } else {
                // 获取锁失败，等待后重试
                usleep(100000);
                $currentBenuser = $this->ben_user();
                return $currentBenuser[$people_id] ?? $this->getDefaultUserData($people_id);
            }
        } catch (\Exception $e) {
            Log::error('更新用户信息失败: ' . $e->getMessage(), [
                'people_id' => $people_id
            ]);
            return $this->getDefaultUserData($people_id);
        } finally {
            if (isset($lock)) {
                $lock->release();
            }
        }
    }
    
    /**
     * 获取用户列表
     */
    public function getList($request, $data = [])
    {
        $cacheKey = 'user_list_all';
        $cacheTime = 1800;
        
        return Cache::remember($cacheKey, $cacheTime, function () {
            // 使用安全的方法获取模型
            $model = $this->getModel();
            
            $fields = ['id', 'nickname', 'avatar'];
            return [
                'data' => $model->select($fields)
                    ->orderBy('id', 'desc')
                    ->get()
                    ->toArray()
            ];
        });
    }
    
    // 获取用户数据
    public function getUserData()
    {
        $cacheKey = 'user_data_mapping';
        $cacheTime = 3600;
        
        return Cache::remember($cacheKey, $cacheTime, function () {
            // 使用安全的方法获取模型
            $model = $this->getModel();
            
            $userData = $model->select()->get();
            $data = [];
            foreach ($userData as $user) {
                $data[$user->userId] = $user->toArray();
            }
            return $data;
        });
    }
    
    // 获取远程用户信息（公开方法）
    public function getServerList($request, $people_id)
    {
        $userData = $this->fetchRemoteUserInfo($people_id);
        
        if (!$userData) {
            $this->error('获取用户信息失败');
        }
        
        return $userData;
    }
    
    // 添加用户信息
    public function addDate($request, $people_id)
    {
        $userData = $this->getServerList($request, $people_id);
        
        if (!$userData) {
            return false;
        }
        
        $lockKey = "user_add_lock:{$people_id}";
        $lock = Cache::lock($lockKey, 10);
        
        try {
            if ($lock->get()) {
                // 使用安全的方法获取模型
                $model = $this->getModel();
                
                $now = date("Y-m-d H:i:s");
                $updateData = [
                    'nickname' => $userData['nickname'] ?? '未知',
                    'avatar' => $userData['avatar'] ?? $this->getDefaultUserData()['avatar'],
                    'userId' => $userData['id'] ?? $people_id,
                    'update_time' => $now,
                ];
                
                $existingUser = $model->where('userId', $updateData['userId'])->first();
                
                if (!$existingUser) {
                    $updateData['create_time'] = $now;
                    $updateData['parent_id'] = '0';
                    $updateData['is_official'] = 2;
                    $model->insert($updateData);
                    Log::info('新增用户成功', ['user_id' => $updateData['userId']]);
                } else {
                    $model->where('userId', $updateData['userId'])->update($updateData);
                    Log::info('更新用户成功', ['user_id' => $updateData['userId']]);
                }
                
                // 清除缓存
                $this->clearUserCache();
                
                return true;
            } else {
                return true;
            }
        } catch (\Exception $e) {
            Log::error('添加用户信息失败: ' . $e->getMessage(), [
                'people_id' => $people_id
            ]);
            return false;
        } finally {
            if (isset($lock)) {
                $lock->release();
            }
        }
    }
    
    // 判断是否是官方账号
    public function isUserOfficial($request, $data = [])
    {
        $people_id = $data['userId'] ?? null;
        
        if (!$people_id) {
            return [
                'msg' => '用户ID不能为空',
                'code' => '2',
                'data' => []
            ];
        }
        
        $cacheKey = 'official_user_ids';
        $cacheTime = 3600;
        
        // 获取官方账号ID列表
        $official_arr = Cache::remember($cacheKey, $cacheTime, function () {
            // 使用安全的方法获取模型
            $model = $this->getModel();
            
            return $model->where('is_official', '1')
                ->pluck('userId')
                ->toArray();
        });
        
        if (in_array($people_id, $official_arr)) {
            $model = $this->getModel();
            $officialUser = $model->where([
                ['userId', '=', $people_id],
                ['is_official', '=', '1'],
            ])->first();
            
            if ($officialUser) {
                $subUsers = $model->where('parent_id', $officialUser->id)->get()->toArray();
                
                return [
                    'msg' => '官方账号',
                    'code' => '1',
                    'data' => $subUsers
                ];
            }
        }
        
        return [
            'msg' => '不是官方账号',
            'code' => '2',
            'data' => []
        ];
    }
    
    /**
     * 安全获取模型实例
     */
    public function getModel()
    {
        if (!$this->model) {
            Log::warning('UserService model is null, reinitializing...');
            // 如果模型为null，重新初始化
            $this->model = app(User::class);
            
            if (!$this->model) {
                Log::error('Failed to reinitialize User model');
                throw new \Exception('User model reinitialization failed');
            }
            
            Log::info('UserService model reinitialized successfully');
        }
        return $this->model;
    }
    
    /**
     * 重置静态状态（用于测试）
     */
    public static function resetStaticState()
    {
        self::$initialized = false;
        self::$staticModel = null;
        self::$staticUrl = null;
        self::$staticGetUserInfo = null;
        self::$staticBenuser = null;
    }
}
